package classesBD;

import aplicacao.funcoes;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Conexao {
  private static Connection con = null;
  
  public static boolean estaConectado(){
    try{
      return !con.isClosed();
    }catch(Exception e){
      return false;
    }  
  }
  
  public static boolean conecta(){
    String url = "jdbc:postgresql://localhost/";
    Properties prop = new Properties();
    File f = new File("Conexao.properties");
    try{
      FileInputStream fIn =  new FileInputStream(f);
      prop.load(fIn);   
    }catch(IOException e){  
         
    };
    String nomeBase = prop.getProperty("base", "DBLP");
    String usuario = prop.getProperty("user","postgres");
    String senha = prop.getProperty("password","postgres");
    try{
      con = DriverManager.getConnection(url += nomeBase, usuario, senha);
      return true;
    } catch(SQLException e){
      return false;
    }
  }
  
  public static String[][] pesquisa(String sql, int numColunas){
    String [][] result = new String[0][0];
    int linha;
    try {
      if (!estaConectado()){
        conecta();
      }
      Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      ResultSet rs = st.executeQuery(sql);
      if(rs.next()){ 
        rs.last();
        linha = rs.getRow();
        result = new String[linha][numColunas];
        rs.first();
        do{
          linha = rs.getRow() - 1;
          for (int coluna=1;coluna<=numColunas;coluna++){
            result[linha][coluna-1] = rs.getString(coluna);
          }
        } while(rs.next());
      }           
    } catch (SQLException ex) {
            funcoes.log("Erro na função pesquisa: " + ex.getMessage());
            return pesquisa(sql, numColunas);
    }
    return result;
  }
  
  public static int executa(String sql) throws SQLException{
    return executa(sql, false);
  }
  
  public static int executa(String sql,boolean retornaID) throws SQLException {
    ResultSet rs;
    try{
      if (con.isClosed()){
        conecta();
      }
      Statement st = con.createStatement();
      
      int rowNumber = st.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
      if (!retornaID){
        return rowNumber;
      }else 
        rs =  st.getGeneratedKeys();
        if (rs.next()){
          return rs.getInt(1);
        }else{
          return 0;
        }
        
      
    }catch(SQLException e){
      funcoes.log("Erro --> SQL: " + sql + " Erro: " + e.getMessage());
      funcoes.log("------------------------------------------------");
      return 0;
    }
  }
  
  public static void fecha() throws SQLException{
    con.close();
  }
  
}
